﻿
using System.Security.Cryptography;
using Framework.EncryptionService.Abstract;

namespace Framework.EncryptionService
{
    /// <summary>
    /// RSA加密服务
    /// </summary>
    public class EncryptionRSAServiceHelps : AbstractEncryptionServiceHelps<EncryptionRSAServiceHelps>
    {
        public override EncryptionServiceHelpsEntity InitEncryption()
        {
            using RSA rsa = RSA.Create(2048);
            return new EncryptionServiceHelpsEntity() { PrivateSecretKey = rsa.ToXmlString(true), PublicSecretKey = rsa.ToXmlString(false) };
        }

        public override byte[] Encrypt(string data)
        {
            data ??= "";
            using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())
            {
                rsa.FromXmlString(PublicSecretKey);
                byte[] plainBytes = data.ConvertToBytes();
                // 使用公钥进行加密
                byte[] bytes = rsa.Encrypt(plainBytes, false);
                //var dataDecrypt = rsa.Decrypt(bytes.ToBase64String().FromBase64String(), false).ConvertToString();
                return bytes;
            }
        }

        public override byte[] Decrypt(byte[] encryptedBytes)
        {
            using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())
            {
                rsa.FromXmlString(PrivateSecretKey);
                return rsa.Decrypt(encryptedBytes, false);
            }
        }
    }
}
